// 自定义脚本

// 格式化JSON显示
function formatJSON(json) {
    if (typeof json === 'string') {
        try {
            json = JSON.parse(json);
        } catch (e) {
            return json;
        }
    }
    return JSON.stringify(json, null, 2);
}

// 初始化所有JSON显示区域
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.json-display').forEach(function(element) {
        try {
            const jsonText = element.textContent.trim();
            if (jsonText) {
                element.textContent = formatJSON(jsonText);
            }
        } catch (e) {
            console.error('JSON格式化错误:', e);
        }
    });
});

// 生成随机颜色
function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) return dateTimeStr;
    
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 格式化日期
function formatDate(dateStr) {
    if (!dateStr) return '';
    
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return dateStr;
    
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

// 导出表格到CSV
function exportTableToCSV(tableId, filename) {
    const table = document.getElementById(tableId);
    if (!table) return;
    
    const rows = table.querySelectorAll('tr');
    if (rows.length === 0) return;
    
    let csvContent = '';
    
    // 添加表头
    const headerCells = rows[0].querySelectorAll('th');
    const headerRow = Array.from(headerCells).map(cell => cell.textContent.trim()).join(',');
    csvContent += headerRow + '\n';
    
    // 添加数据行
    for (let i = 1; i < rows.length; i++) {
        const cells = rows[i].querySelectorAll('td');
        const row = Array.from(cells).map(cell => cell.textContent.trim()).join(',');
        csvContent += row + '\n';
    }
    
    // 创建下载链接
    const encodedUri = encodeURI('data:text/csv;charset=utf-8,' + csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    
    // 点击下载链接
    link.click();
    
    // 移除下载链接
    document.body.removeChild(link);
}

// 生成时间线可视化
function generateTimeline(timeSlots, containerId) {
    const timeline = document.getElementById(containerId);
    if (!timeline) return;
    
    timeline.innerHTML = '';
    
    // 按照活动类型分组
    const activityGroups = {};
    const activityColors = {};
    let colorIndex = 1;
    
    timeSlots.forEach(function(slot) {
        const activity = slot.activity;
        
        if (!activityGroups[activity]) {
            activityGroups[activity] = [];
            activityColors[activity] = colorIndex % 11; // 11种颜色循环
            colorIndex++;
        }
        
        activityGroups[activity].push(slot);
    });
    
    // 创建时间线
    const timeSlotCount = timeSlots.length;
    
    // 创建时间刻度
    const timeScaleRow = document.createElement('div');
    timeScaleRow.className = 'timeline-row';
    
    const timeScaleLabel = document.createElement('div');
    timeScaleLabel.className = 'timeline-label';
    timeScaleLabel.textContent = '时间';
    
    const timeScaleSlots = document.createElement('div');
    timeScaleSlots.className = 'timeline-slots';
    
    timeSlots.forEach(function(slot) {
        const timeSlot = document.createElement('div');
        timeSlot.className = 'timeline-slot';
        timeSlot.style.backgroundColor = '#f8f9fa';
        timeSlot.style.color = '#212529';
        timeSlot.textContent = slot.time_slot;
        timeScaleSlots.appendChild(timeSlot);
    });
    
    timeScaleRow.appendChild(timeScaleLabel);
    timeScaleRow.appendChild(timeScaleSlots);
    timeline.appendChild(timeScaleRow);
    
    // 创建活动时间线
    for (const activity in activityGroups) {
        const activityRow = document.createElement('div');
        activityRow.className = 'timeline-row';
        
        const activityLabel = document.createElement('div');
        activityLabel.className = 'timeline-label';
        activityLabel.textContent = activity;
        
        const activitySlots = document.createElement('div');
        activitySlots.className = 'timeline-slots';
        
        // 创建空白槽
        for (let i = 0; i < timeSlotCount; i++) {
            const emptySlot = document.createElement('div');
            emptySlot.className = 'timeline-slot';
            emptySlot.style.backgroundColor = 'transparent';
            activitySlots.appendChild(emptySlot);
        }
        
        // 填充活动槽
        activityGroups[activity].forEach(function(slot) {
            const index = timeSlots.findIndex(s => s.time_slot === slot.time_slot);
            if (index !== -1) {
                const activitySlot = activitySlots.children[index];
                activitySlot.className = `timeline-slot activity-color-${activityColors[activity]} timeline-tooltip`;
                activitySlot.setAttribute('data-tooltip', `${slot.time_slot}: ${activity} (${slot.caregiver})`);
                activitySlot.textContent = slot.caregiver;
            }
        });
        
        activityRow.appendChild(activityLabel);
        activityRow.appendChild(activitySlots);
        timeline.appendChild(activityRow);
    }
}

// 科技风格交互效果
document.addEventListener('DOMContentLoaded', function() {
    // 初始化提示气泡
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 卡片悬浮效果增强
    const techCards = document.querySelectorAll('.tech-card');
    techCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 0 20px rgba(5, 217, 232, 0.9)';
        });
        card.addEventListener('mouseleave', function() {
            this.style.transform = '';
            this.style.boxShadow = '';
        });
    });

    // 为导航链接添加激活指示器动画
    const navLinks = document.querySelectorAll('.tech-nav-link');
    navLinks.forEach(link => {
        link.addEventListener('mouseenter', function() {
            if (!this.classList.contains('active')) {
                this.style.borderLeftColor = 'var(--tech-primary)';
                this.style.backgroundColor = 'rgba(5, 217, 232, 0.1)';
            }
        });
        link.addEventListener('mouseleave', function() {
            if (!this.classList.contains('active')) {
                this.style.borderLeftColor = 'transparent';
                this.style.backgroundColor = '';
            }
        });
    });

    // 表单控件增强效果
    const techFormControls = document.querySelectorAll('.tech-form-control, .tech-form-select');
    techFormControls.forEach(control => {
        control.addEventListener('focus', function() {
            this.parentElement.classList.add('tech-focused');
        });
        control.addEventListener('blur', function() {
            this.parentElement.classList.remove('tech-focused');
        });
    });

    // 为班制模式选择添加联动效果
    const shiftModeSelect = document.getElementById('shift_mode');
    const customShiftsSection = document.getElementById('customShiftsSection');
    
    if (shiftModeSelect && customShiftsSection) {
        // 初始化时检查
        if (shiftModeSelect.value === '4') {
            customShiftsSection.style.display = 'block';
        } else {
            customShiftsSection.style.display = 'none';
        }

        // 监听选择变化
        shiftModeSelect.addEventListener('change', function() {
            if (this.value === '4') {
                customShiftsSection.style.display = 'block';
            } else {
                customShiftsSection.style.display = 'none';
            }
            
            // 根据班制显示/隐藏班次输入
            const shift1Section = document.getElementById('shift1Section');
            const shift2Section = document.getElementById('shift2Section');
            const shift3Section = document.getElementById('shift3Section');
            
            if (shift1Section && shift2Section && shift3Section) {
                if (this.value === '1') {
                    shift1Section.style.display = 'block';
                    shift2Section.style.display = 'none';
                    shift3Section.style.display = 'none';
                } else if (this.value === '2') {
                    shift1Section.style.display = 'block';
                    shift2Section.style.display = 'block';
                    shift3Section.style.display = 'none';
                } else {
                    shift1Section.style.display = 'block';
                    shift2Section.style.display = 'block';
                    shift3Section.style.display = 'block';
                }
            }
        });
    }

    // 表单提交动画效果
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const submitButton = this.querySelector('[type="submit"]');
            if (submitButton) {
                submitButton.disabled = true;
                submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 提交中...';
            }
        });
    });

    // 时间线动画效果
    const timelineItems = document.querySelectorAll('.tech-timeline-item');
    if (timelineItems.length > 0) {
        timelineItems.forEach((item, index) => {
            item.style.opacity = '0';
            item.style.transform = 'translateX(-20px)';
            item.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
            
            setTimeout(() => {
                item.style.opacity = '1';
                item.style.transform = 'translateX(0)';
            }, 100 * (index + 1));
        });
    }

    // 页面加载完成后淡入效果
    const mainContent = document.querySelector('.tech-main');
    if (mainContent) {
        mainContent.style.opacity = '0';
        mainContent.style.transition = 'opacity 0.5s ease';
        
        setTimeout(() => {
            mainContent.style.opacity = '1';
        }, 100);
    }

    // 为时间选择器添加时间格式验证
    const timeInputs = document.querySelectorAll('input[type="time"]');
    timeInputs.forEach(input => {
        input.addEventListener('change', function() {
            const timePattern = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
            if (!timePattern.test(this.value)) {
                this.setCustomValidity('请使用有效的时间格式：HH:MM');
            } else {
                this.setCustomValidity('');
            }
        });
    });

    // 数值范围验证
    const numberInputs = document.querySelectorAll('input[type="number"]');
    numberInputs.forEach(input => {
        input.addEventListener('input', function() {
            const min = parseFloat(this.getAttribute('min'));
            const max = parseFloat(this.getAttribute('max'));
            const value = parseFloat(this.value);
            
            if (!isNaN(min) && !isNaN(value) && value < min) {
                this.setCustomValidity(`值必须大于或等于 ${min}`);
            } else if (!isNaN(max) && !isNaN(value) && value > max) {
                this.setCustomValidity(`值必须小于或等于 ${max}`);
            } else {
                this.setCustomValidity('');
            }
        });
    });
});
